import request from '@/api/request'
import type { ArticleSummary, ArticleListQuery, ArticleListResp, ArticleRecordRaw } from '@/types/Article'
import { normalizeArticleSummary } from '@/types/Article'

export async function fetchArticles(params: ArticleListQuery) {
  console.log('Fetching articles with params:', params)
  const res = await request<ArticleListResp>({
    url: '/articles/list',
    method: 'GET',
    params: params,
  })
  const raw: any = (res as any)?.data ?? res
  let list: any[] = []
  if (Array.isArray(raw?.list)) list = raw.list
  else if (Array.isArray(raw)) list = raw
  const total = raw?.total ?? list.length
  return { list: normalizeArticles(list), total }
}

function normalizeArticles(arr: any[]): ArticleSummary[] {
  return (arr as ArticleRecordRaw[]).map((a) => normalizeArticleSummary(a))
}

// 创建文章
export interface ArticleCreatePayload {
  title: string
  category?: string
  // 若使用 JSON 方式创建，可传封面图 URL/base64；
  // 统一文件上传时，该字段可忽略，改为通过 FormData 的文件字段传递
  coverImage?: string
  description?: string
  content?: string
  status?: 'DRAFT' | 'PUBLISHED' | 'ARCHIVED'
  tags?: string[]
}

// 允许同时支持 JSON 与 FormData（文件上传）两种方式
export async function createArticle(payload: ArticleCreatePayload | FormData) {
  console.log('Creating article with payload:', payload instanceof FormData ? '[FormData]' : payload)
  return request<any>({
    url: '/articles/create-article',
    method: 'POST',
    data: payload,
  })
}

// 仅上传封面图，后端返回文章 ID（或草稿 ID）和封面地址
export async function uploadArticleCover(file: File) {
  const fd = new FormData()
  // 后端采用 @RequestParam("file") MultipartFile file
  fd.append('file', file)
  // console.log('Uploading article cover:', file)
  return request<any>({
    url: '/articles/upload-cover',
    method: 'POST',
    data: fd,
  })
}

// 二次提交文章其他信息（标题/正文等），引用第一步返回的文章 ID
export interface ArticleMetaPayload {
  title: string
  category?: string
  coverUrl?: string
  description?: string
  content?: string
  status?: 'DRAFT' | 'PUBLISHED' | 'ARCHIVED'
  tags?: string[]
}

export async function createArticleMeta(payload: ArticleMetaPayload) {
  // console.log('Creating article meta with payload:', payload)
  return request<any>({
    url: '/articles/create-article-meta', // 或 '/articles/create-article' 若后端复用接口
    method: 'POST',
    data: payload,
  })
}

